import puppeteer, { Page } from 'puppeteer';
import { getUserAgent } from "../../utils/crawlerUtils";
// const fs = require('fs');
import * as fs from 'fs';

class KwaiCrawler {
    private _loginType: string = '';
    private _userAgent: string;
    private _page;

    constructor() {
        this._userAgent = getUserAgent();
    }

    initConfig(loginType: string) {
        this._loginType = loginType;
    }

    async start() {
        // console.log(this._loginType);
        const browser = await puppeteer.launch({headless: false});
        const page = await browser.newPage();
        this._page = page;
        await page.setUserAgent(this._userAgent);
        await this.setCookie();
        await page.goto('https://v.kuaishou.com/nXsnMl');
        await page.setViewport({width: 1366, height: 768});
        await page.addScriptTag({ 'path': 'libs/stealth.min.js' });
        // await closeVerify(page);
    }

    async saveCookie() {
        await this._page.goto('https://id.kuaishou.com/');
        const cookies = await this._page.cookies();
        const userId = cookies.find(item => item.name === 'userId').value;
        fs.writeFileSync(`./userData/${userId}`, JSON.stringify(cookies));
    }

    async setCookie() {
        const data = fs.readFileSync('./test');
        const cookies = JSON.parse(data.toString());
        for (const cookie of cookies) {
          // if (cookie.expires === -1) {
          //   cookie.expires = new Date();
          // } else {
          //   cookie.expires = new Date(cookie.expires);
          // }
          // cookie.expires = Date.now() + 86400000;
        //   if (cookie.name === 'userId') {
        //     console.log("sdsdsdsdsd")
        //     await this._page.setCookie({
        //       name: cookie.name,
        //       value: cookie.value,
        //       domain: 'id.kuaishou.com',
        //       path: cookie.path,
        //       expires: Date.now() + 86400000, 
        //       secure: true, // 仅在 HTTPS 连接上发送 cookie
        //       httpOnly: true 
        //     });
        //   }
          await this._page.setCookie({
            name: cookie.name,
            value: cookie.value,
            domain: cookie.domain,
            path: cookie.path,
            expires: Date.now() + 86400000, 
            secure: true, // 仅在 HTTPS 连接上发送 cookie
            httpOnly: true 
          });
        }
    }

    launchBrowser() {

    }
}

/**
 * 关闭验证
 * @param page 
 */
const closeVerify = async (page: Page) => {
    const frameHandle = await page.$('iframe'); // 获取iframe元素的句柄
    if (frameHandle) {
        const frame = await frameHandle.contentFrame();
        // 如果有安全验证  进行关闭
        if (frame) {
            await frame.waitForSelector('.icon-close');
            await frame.click('.icon-close');
            await page.waitForFunction(() => !document.querySelector('iframe'));
        }
    }
};

// /**
//  * 评论
//  * @param page 
//  */
// const comment = async (page: Page) => {

// };

export default KwaiCrawler;